import axios from 'axios'
import {globalConst} from '@constants/globalConst.ts'
import ResponseResult from '@models/ReturnResult.ts'
import {useGlobalConfirm} from '@utils/ConfirmDialogPlugin.ts'
import {isNull} from '@utils/stringUtil.ts'
import {getUser, getUserToken, setUser, setUserTokenByResponse} from "@stores/localStorage.js"
import {Users} from "@models/User.js";
import Cookie from "js-cookie";

const axiosInstance = axios.create({
    baseURL: globalConst.baseUrl,
    timeout: 999999,
    withCredentials: true
})

// ====================== 请求拦截器 ======================
axiosInstance.interceptors.request.use(
    (config) => {
        // 如果,需要认证的路径生,未手动设置 token，则使用默认 token
        const requestUrl = config.url;
        if (isNull(config.headers[globalConst.tokenName]) && requestUrl?.includes('api/user')) {
            const token = getUserToken()
            config.headers[globalConst.tokenName] = token ?? 'null'
        }
        return config
    },
    (error) => Promise.reject(error)
)

// ====================== 响应拦截器 ======================
axiosInstance.interceptors.response.use(
    async (response) => {
        const data = response.data

        // 系统消息提示
        if (!isNull(data.map)) {
            if (!isNull(data.map[globalConst.systemMsg]))
                alert(`系统消息：${data.map[globalConst.systemMsg] ?? '未知消息'}`)
        }

        // 尝试更新 token（如果响应里有的话）
        setUserTokenByResponse(response)

        // 刷新本地缓存
        getUser()

        // 错误处理
        if (data.hasError) {
            let errorData: any
            try {
                errorData = ResponseResult.fromApiResponse(data)
                if (errorData.errorNum >= 2000 && errorData.errorNum < 3000) {
                    if (errorData.errorNum === 2007) {
                        alert("您的会话已经过期了,请重新登录~")
                    } else {
                        alert("您的会话出现了错误原因是:" + errorData.msg + ",为避免显示异常已经自动将您下线,为了确保您的账号安全请及时联系管理员进行处理!")
                    }
                    setUser(Users.fromApiResponse({
                        userName: Cookie.get('114514UserName') || '游客',
                        coin: parseInt(Cookie.get('114514UserCoin') || '0'),
                        userHeadPortraitUrl: Cookie.get('114514UserHeadPortraitUrl') || null,
                        userId: parseInt(Cookie.get('114514UserId') || '-1'),
                        jurisdiction: parseInt(Cookie.get('114514UserJurisdiction') || '0')
                    }))
                    localStorage.removeItem(globalConst.tokenName)
                    getUser()
                    return response
                }
            } catch (e) {
                errorData = data
            }
            const msg = data.msg || '未知错误'
            const confirm = useGlobalConfirm()
            const goErrorPage = await confirm(
                `请求失败：${msg}\n是否跳转错误页查看详细错误信息？`,
                {
                    title: '请求错误',
                    trueText: '跳转',
                    falseText: '忽略'
                }
            )
            if (goErrorPage) {
                localStorage.setItem('global_error', JSON.stringify({
                    msg,
                    detail: errorData
                }))
                location.href = '/src/page/error/index.html'
            }

            return Promise.reject(data)
        }
        return response
    },
    async (error) => {
        const confirm = useGlobalConfirm()
        const goErrorPage = await confirm(
            '网络错误或服务器异常，是否跳转错误页？',
            {
                title: '系统异常',
                trueText: "跳转",
                falseText: "忽略"
            }
        )

        if (goErrorPage) {
            localStorage.setItem('global_error', JSON.stringify({
                msg: '网络出现错误!',
                detail: error,
            }))
            location.href = '/src/page/error/index.html'
        }

        return Promise.reject(error)
    }
)

export default axiosInstance
